#if 1
#include "xparameters.h"
#include "xcanps.h"
#include "xil_printf.h"

#define CAN_DEVICE_ID      XPAR_XCANPS_0_DEVICE_ID
#define TEST_MESSAGE_ID    0x123  // 示例帧 ID

XCanPs Can;

int main() {
    int Status;
    XCanPs_Config *Config;
    u32 TxFrame[XCANPS_MAX_FRAME_SIZE];
    u32 RxFrame[XCANPS_MAX_FRAME_SIZE];

    // 初始化 CAN 控制器
    Config = XCanPs_LookupConfig(CAN_DEVICE_ID);
    if (Config == NULL) {
        xil_printf("配置失败\r\n");
        return XST_FAILURE;
    }

    Status = XCanPs_CfgInitialize(&Can, Config, Config->BaseAddr);
    if (Status != XST_SUCCESS) {
        xil_printf("初始化失败\r\n");
        return XST_FAILURE;
    }

    XCanPs_Reset(&Can);
    while (XCanPs_IsRxEmpty(&Can) == 0) {
        XCanPs_Recv(&Can, RxFrame);  // 清除残留帧
    }

    XCanPs_EnterMode(&Can, XCANPS_MODE_CONFIG);
    while (XCanPs_GetMode(&Can) != XCANPS_MODE_CONFIG);

    XCanPs_SetBaudRatePrescaler(&Can, 9);      // 示例设置，需根据时钟计算波特率
    XCanPs_SetBitTiming(&Can, 2, 1, 12);         // 时间段设置（配置适合你的板子）



    XCanPs_EnterMode(&Can, XCANPS_MODE_NORMAL);
    int timeout = 10;

    while (XCanPs_GetMode(&Can) != XCANPS_MODE_NORMAL && timeout-- > 0)
    {
    	sleep(2);
    	XCanPs_EnterMode(&Can, XCANPS_MODE_NORMAL);
    	sleep(2);
    };

    if (timeout <= 0) {
        xil_printf("进入NORMAL模式失败，请检查硬件连接！\r\n");
        return -1;
    }

    xil_printf("CAN 正常模式，开始发送\r\n");

    // 构造发送帧
    TxFrame[0] = XCanPs_CreateIdValue(TEST_MESSAGE_ID, 0, 0, 0, 0);  // 标准帧，非远程帧
    TxFrame[1] = 0x11223344;
    TxFrame[2] = 0x55667788;


    while(1)
    {
    	XCanPs_Send(&Can, TxFrame);

    	    xil_printf("发送完成，等待接收...\r\n");
    	    sleep(1);
    	    // 等待接收
    	       while (XCanPs_IsRxEmpty(&Can));

    	       XCanPs_Recv(&Can, RxFrame);
    	       u32 id_raw = (RxFrame[0] >> 18) & 0x7FF;  // 0x7FF = 11 bits mask
    	       xil_printf("收到帧 ID = 0x%03X\r\n", id_raw);

    	       xil_printf("数据部分: %08X %08X\r\n", RxFrame[1], RxFrame[2]);

    }
    return 0;
}

#else



#include "xparameters.h"
#include "xuartps.h"
#include "xil_printf.h"

#define UART_DEVICE_ID  XPAR_PS7_UART_1_DEVICE_ID
#define BAUD_RATE  115200

XUartPs Uart_Ps;

int main() {
    XUartPs_Config *Config;
    int Status;

    // 初始化UART驱动
    Config = XUartPs_LookupConfig(UART_DEVICE_ID);
    Status = XUartPs_CfgInitialize(&Uart_Ps, Config, Config->BaseAddress);
    if (Status != XST_SUCCESS) {
        return XST_FAILURE;
    }

    // 设置波特率
    XUartPs_SetBaudRate(&Uart_Ps, BAUD_RATE);

    // 发送欢迎信息
    const char welcome_msg[] = "\nZynq UART Echo Test - Type characters (Press ESC to exit)\n\r";
    XUartPs_Send(&Uart_Ps, (u8*)welcome_msg, sizeof(welcome_msg));

    // 串口回传循环
    while (1) {
        u8 recv_char;

        // 阻塞式接收字符
        while (XUartPs_Recv(&Uart_Ps, &recv_char, 1) == 0);

        // 退出条件 (ESC键)
        if (recv_char == 0x1B) break;

        // 回显接收到的字符
        XUartPs_Send(&Uart_Ps, &recv_char, 1);

        // 添加回车换行
        if (recv_char == '\r') {
            u8 newline = '\n';
            XUartPs_Send(&Uart_Ps, &newline, 1);
        }
    }

    const char exit_msg[] = "\n\rExit UART test.\n\r";
    XUartPs_Send(&Uart_Ps, (u8*)exit_msg, sizeof(exit_msg));
    return 0;
}


#endif

//串口中断示例-已验证

#include "xparameters.h"
#include "stdio.h"
#include "xuartps.h"
#include "xuartps_hw.h"
#include "xscugic.h"
#define UART_1_DEVICE_ID XPAR_PS7_UART_1_DEVICE_ID
#define INTR_DEVICE_ID		XPAR_SCUGIC_SINGLE_DEVICE_ID
#define UART_INT_IRQ_ID		XPAR_XUARTPS_1_INTR
XUartPs Uart_Inst;
XScuGic ScuGic_Inst;
int uart_init();
void intr_init(XScuGic *intr, XUartPs *uart);
void UartIntr_Handler(void *call_back_ref);
int main(){

	//uart初试化函数
	uart_init();
	xil_printf("intr\n");
	//中断初始化
	intr_init(&ScuGic_Inst,&Uart_Inst);
	while(1);
	return 0;
}

//uart初始化
int uart_init(){
	XUartPs_Config *UartPs_Cfg;
	int Status;
	//查找配置信息
	UartPs_Cfg= XUartPs_LookupConfig(UART_1_DEVICE_ID);
	//对uart控制器进行初始化
	XUartPs_CfgInitialize(&Uart_Inst, UartPs_Cfg, UartPs_Cfg->BaseAddress);
	//检测硬件搭建是否正确
	Status = XUartPs_SelfTest(&Uart_Inst);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}
	//设置波特率
	XUartPs_SetBaudRate(&Uart_Inst,115200);
	//设置RXFIFO触发阈值
	XUartPs_SetFifoThreshold(&Uart_Inst,1);
	//设置操作模式
	XUartPs_SetOperMode(&Uart_Inst, XUARTPS_OPER_MODE_NORMAL);

	return XST_SUCCESS;
}

//中断初始化
void intr_init(XScuGic *intr, XUartPs *uart){
	XScuGic_Config *IntcConfig;
	//中断控制器初始化
	IntcConfig = XScuGic_LookupConfig(INTR_DEVICE_ID);
	XScuGic_CfgInitialize(intr,IntcConfig,IntcConfig->CpuBaseAddress);
	Xil_ExceptionInit();
	Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT,
					(Xil_ExceptionHandler) XScuGic_InterruptHandler,
					(void *)intr);
	Xil_ExceptionEnable();
	//为中断设置中断处理函数
	XScuGic_Connect(intr, UART_INT_IRQ_ID,
					  (Xil_ExceptionHandler) UartIntr_Handler,
					  (void *) uart);
	//设置触发类型
	XUartPs_SetInterruptMask(uart, XUARTPS_IXR_RXOVR);
	//使能中断
	XScuGic_Enable(intr, UART_INT_IRQ_ID);

}
//中断处理函数
void UartIntr_Handler(void *call_back_ref){
	XUartPs *uartinst =(XUartPs *)call_back_ref;
	u32 read_data = 0;
	u32 intr_status;
	//读取中断ID寄存器
	intr_status = XUartPs_ReadReg(uartinst->Config.BaseAddress,
			XUARTPS_IMR_OFFSET);//读取掩码
	intr_status &= XUartPs_ReadReg(uartinst->Config.BaseAddress,
			XUARTPS_ISR_OFFSET);//读取状态
	if(intr_status & (u32)XUARTPS_IXR_RXOVR){
		read_data = XUartPs_RecvByte(XPAR_PS7_UART_1_BASEADDR);//接收发送的字节
		XUartPs_WriteReg(uartinst->Config.BaseAddress,XUARTPS_ISR_OFFSET,
				XUARTPS_IXR_RXOVR);//清除中断状态
	}
	//设置发送
	XUartPs_SendByte(XPAR_PS7_UART_1_BASEADDR,read_data);
}


//==========================================